<template>
  <div class="course-manage">
    <div class="header" v-if="userStore.user?.role !== 'STUDENT'">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">新增课程</el-button>
    </div>
    <el-table :data="courseStore.courses" style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="title" label="课程名称"></el-table-column>
      <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="teacherId" label="教师姓名" width="150">
        <template #default="{ row }">
          {{ getTeacherName(row.teacherId) }}
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="100"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          {{ statusMap[row.status] || row.status }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            v-if="userStore.user?.role !== 'STUDENT'"
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            v-if="userStore.user?.role !== 'STUDENT'"
            type="danger"
            size="small"
            @click="courseStore.deleteCourse(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增课程对话框 -->
    <el-dialog title="新增课程" v-model="createDialogVisible" width="30%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="createForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="createForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherId">
          <el-select v-model="createForm.teacherId" placeholder="请选择教师">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.id"
              :label="teacher.realName"
              :value="teacher.id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="createForm.category"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createCourse" :icon="Plus">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改课程对话框 -->
    <el-dialog title="修改课程" v-model="editDialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="editFormRef">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="教师姓名" prop="teacherId">
          <el-select v-model="editForm.teacherId" placeholder="请选择教师">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.id"
              :label="teacher.realName"
              :value="teacher.id.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="editForm.category"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateCourse" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { useCourseStore } from '@/stores/api/course';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const statusMap = {
  PENDING: '等待中',
  APPROVED: '已通过',
  REJECTED: '已拒绝',
};

const courseStore = useCourseStore();
const userStore = useUserStore();

const createDialogVisible = ref(false);
const editDialogVisible = ref(false);

const createForm = ref({
  title: '',
  description: '',
  teacherId: 0,
  category: '',
});

const editForm = ref({
  id: 0,
  title: '',
  description: '',
  teacherId: 0,
  category: '',
});

const formRules = ref<FormRules>({
  title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  teacherId: [{ required: true, message: '请选择教师', trigger: 'change' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
});

const teachers = ref<any[]>([]);
const createFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const getTeacherName = (teacherId: number) => {
  const teacher = teachers.value.find(t => t.id === teacherId);
  return teacher ? teacher.realName : '未知';
};

const fetchTeachers = async () => {
  try {
    const users = await userStore.fetchUsers();
    teachers.value = users.filter(user => user.role === 'TEACHER');
  } catch (error) {
    ElMessage.error('获取教师列表失败');
  }
};

const showCreateDialog = () => {
  createForm.value = { title: '', description: '', teacherId: userStore.user?.role === 'TEACHER' ? userStore.user.id : 0, category: '' };
  createDialogVisible.value = true;
};

const createCourse = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await courseStore.createCourse(createForm.value);
        createDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

const showEditDialog = (course: any) => {
  editForm.value = { ...course, id: course.id };
  editDialogVisible.value = true;
};

const updateCourse = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await courseStore.updateCourse(editForm.value);
        editDialogVisible.value = false;
      } catch (error) {
        // 错误已在 store 中处理
      }
    }
  });
};

onMounted(() => {
  courseStore.fetchCourses();
  fetchTeachers();
});
</script>

<style scoped>
.course-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}

.el-button i + span {
  margin-left: 8px;
}

.el-select {
  width: 100%;
}
</style>